<template>
  <div class="wrapper-page">
    <div class="left-wratter">
      <img src="@/assets/images/login/100buy_login.png" class="login-img" alt="">
    </div>
    <div class="right-wrapper">
      <div class="right-content">
        <!-- <img src="@/assets/images/home/logo.png" class="logo-img" alt=""> -->
        <div class="title-text">{{ $t("header.logo_text") }}</div>
        <div class="div-input">
          <Input size="large" v-model="form.username" @on-change="validateEmail"
            :placeholder="$t('login.enterEmailAccount')" />
          <span v-if="!isValidEmail" style="color: red;">{{ $t("login.validEmail") }}</span>
        </div>
        <div class="div-input">
          <Input size="large" v-model="form.password" :placeholder="$t('login.enterPassword')" password
            type="password" />
        </div>
        <Button class="btn" @click="onLogin" :loading="loading" type="primary" size="large" long>
          {{ $t('public.login') }}
        </Button>
        <div class="fun">
          <router-link class="fun-item" to="/register">
            <span class="text-tips">{{ $t('public.register') }}
              <Icon type="ios-arrow-forward" />
            </span>
          </router-link>
          <router-link class="fun-item" to="/forgot"> {{ $t('login.forgotPassword') }}</router-link>
        </div>
        <Divider>
          <div class="other-text">{{ $t("public.otherLoginChannel") }}</div>
        </Divider>
        <div class="login-way">
          <div class="way">
            <!-- <img src="@/assets/images/login/apple.png" alt=""> -->
            <img src="@/assets/images/login/google.png" @click="loginWithGoogle" alt="">
            <img src="@/assets/images/login/discord.svg" @click="loginWithDiscord" alt="">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { eventBus } from '@/main'; // 引入全局事件总线
import { pointUser } from "@/common/point/api-hook";//打点日志
import { GoogleOAuthProvider } from 'google-oauth-gsi';

const googleProvider = new GoogleOAuthProvider({
  clientId: '742076253847-gtutc8pr8n85t27hju53m7srmjjdumgu.apps.googleusercontent.com',
  onScriptLoadError: () => console.log('onScriptLoadError'),
  onScriptLoadSuccess: () => console.log('onScriptLoadSuccess'),
});
import { login, randomImage, getRoute, getCallback, loginWithGoogleOauth2 } from "@/api/user";
import { mapState } from "vuex";
export default {
  name: 'login-view',
  data() {
    return {
      appName: process.env.VUE_APP_NAME,
      loading: false,
      form: {
        captcha: '', // 验证码
        checkKey: '', // 	验证码key
        password: '', // 密码
        username: '', // 账号
        provisionalToken: '',
      },
      isValidEmail: true,
      defaultForm: {
        countryCode: "US"
      }
    }
  },
  computed: {
    ...mapState({
      userLanguage: state => state.user.userLanguage,
      userCurrency: (state) => state.user.userCurrency
    })
  },
  created() {
    if (window.location.search.length > 0) {
      this.eachMeth(window.location.search);
    }
    const pathUrl = localStorage.getItem("prevPage");
    if (pathUrl) {
      const checkWords = ["login", "register", "forgot"];
      for (const word of checkWords) {
        if (pathUrl.includes(word)) {
          localStorage.removeItem("prevPage");
          break; // 如果找到匹配的，执行删除操作后就可以跳出循环了，因为目的已经达到
        }
      }
    }
  },

  methods: {
    loginWithGoogle() {
      // 登录埋点
      if (this.$analytics) {
        this.$analytics.logEvent('login', { methods: 'google' });
      }

      const googleLoginConnector = googleProvider.useGoogleLogin({
        flow: 'implicit',
        onSuccess: (res) => this.handleCredentialResponse(res),
        onError: (err) => console.error('Failed to login with google', err),
      });
      googleLoginConnector();
    },
    loginWithDiscord() {
      // 登录埋点
      if (this.$analytics) {
        this.$analytics.logEvent('login', { methods: 'Discord' });
      }

      this.getJumpUrl();
    },
    async handleCredentialResponse(response) {
      this.defaultForm.source = 'google';
      this.defaultForm.currencyCode = this.userCurrency.code;
      this.defaultForm.lang = this.userLanguage.code;
      this.defaultForm.inviteCode = sessionStorage.getItem("INVITE_CODE");
      this.defaultForm.activityCode = this.$route.query.activityCode;
      this.defaultForm.code = response.access_token
      loginWithGoogleOauth2(this.defaultForm).then(res => {
        this.loading = false;
        localStorage.setItem('USER_TOKEN', res.result.xaccessToken);
        this.$store.commit('setUserToken', res.result.xaccessToken);
        this.$Message.success(this.$t('login.loginSuccess'));
        this.$store.dispatch('getUserInfo');

        pointUser('login');

        if (this.$route.query.redirection) {
          this.$router.push(this.$route.query.redirection);
        } else {
          this.$router.push('/');
        }
        if (window.ssq) {
          ssq.push('clearUser');
          ssq.push('setLoginInfo', {
            user_id: res.result.userInfo.id, // 加密后的用户id, 必填！
            user_name: res.result.userInfo.userName, // 对应用户名
            language: 'en-US', // 对应用户语言
            email: res.result.userInfo.email,
          });
        }
      })

    },
    eachMeth(val) {
      let urlParams = new URLSearchParams(val.split('?')[1]);
      let stateValue = urlParams.get('state');
      let codeValue = urlParams.get('code');
      let sourceValue = urlParams.get('source');
      if (!sourceValue) {
        sourceValue = 'google';
      }
      if (sourceValue === 'google') {
        if ((urlParams.has('state') && stateValue !== null && stateValue !== '') && (urlParams.has('code') && codeValue !== null && codeValue !== '')) {
          this.googleBack(sourceValue, val);
        }
      } else {
        this.discordBack(sourceValue, codeValue, stateValue);
      }
    },
    googleBack(sourceValue, val) {
      getCallback(sourceValue, val).then(res => {
        localStorage.setItem('USER_TOKEN', res.result.xaccessToken);
        this.$store.commit('setUserToken', res.result.xaccessToken);
        this.$Message.success(this.$t('login.loginSuccess'));
        this.$store.dispatch('getUserInfo');

        pointUser('login');

        // 登录之后回到之前查看的页面
        const prevPage = localStorage.getItem('prevPage');
        localStorage.removeItem('prevPage');
        if (prevPage) {
          window.location.href = prevPage;
        } else if (this.$route.query.redirection) {
          this.$router.push(this.$route.query.redirection);
        } else {
          this.$router.push('/');
        }
        if (window.ssq) {
          ssq.push('clearUser');
          ssq.push('setLoginInfo', {
            user_id: res.result.userInfo.id, // 加密后的用户id, 必填！
            user_name: res.result.userInfo.userName, // 对应用户名
            language: 'en-US', // 对应用户语言
            email: res.result.userInfo.email,
          });
        }
      })
    },
    discordBack(sourceValue, codeValue, stateValue) {
      this.defaultForm.source = 'discord';
      this.defaultForm.currencyCode = this.userCurrency.code;
      this.defaultForm.lang = this.userLanguage.code;
      this.defaultForm.inviteCode = sessionStorage.getItem("INVITE_CODE") || '';
      this.defaultForm.code = codeValue;
      this.defaultForm.state = stateValue;
      loginWithGoogleOauth2(this.defaultForm).then(res => {
        this.loading = false;
        localStorage.setItem('USER_TOKEN', res.result.xaccessToken);
        this.$store.commit('setUserToken', res.result.xaccessToken);
        this.$Message.success(this.$t('login.loginSuccess'));
        this.$store.dispatch('getUserInfo');

        pointUser('login');

        if (this.$route.query.redirection) {
          this.$router.push(this.$route.query.redirection);
        } else {
          this.$router.push('/');
        }
        if (window.ssq) {
          ssq.push('clearUser');
          ssq.push('setLoginInfo', {
            user_id: res.result.userInfo.id, // 加密后的用户id, 必填！
            user_name: res.result.userInfo.userName, // 对应用户名
            language: 'en-US', // 对应用户语言
            email: res.result.userInfo.email,
          });
        }
      })
    },
    validateEmail() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      this.isValidEmail = emailRegex.test(this.form.username);
    },
    onLogin() {
      // 登录埋点
      if (this.$analytics) {
        this.$analytics.logEvent('login', { methods: 'email' });
      }

      this.loading = true;
      this.form.username = this.form.username.trim()
      this.form.password = this.form.password.trim()
      this.form.captcha = this.form.captcha.trim()
      login(this.form).then((res) => {
        // 登录成功后触发事件
        eventBus.$emit('loginSuccess');
        this.loading = false;
        localStorage.setItem('USER_TOKEN', res.result.xaccessToken);
        this.$store.commit('setUserToken', res.result.xaccessToken);
        this.$Message.success(this.$t('login.loginSuccess'));
        this.$store.dispatch('getUserInfo');

        pointUser('login');

        // 登录之后回到之前查看的页面
        const prevPage = localStorage.getItem('prevPage');
        localStorage.removeItem('prevPage');
        if (prevPage) {
          window.location.href = prevPage;
        } else if (this.$route.query.redirection) {
          this.$router.push(this.$route.query.redirection);
        } else {
          this.$router.push('/');
        }

        if (window.ssq) {
          ssq.push('clearUser');
          ssq.push('setLoginInfo', {
            user_id: res.result.userInfo.id, // 加密后的用户id, 必填！
            user_name: res.result.userInfo.userName, // 对应用户名
            language: 'en-US', // 对应用户语言
            email: res.result.userInfo.email,
          });
        }
      }).catch(() => {
        this.loading = false;
      })
    },
    getJumpUrl() {
      this.defaultForm.source = 'discord';
      this.defaultForm.currencyCode = this.userCurrency.code;
      this.defaultForm.lang = this.userLanguage.code;
      this.defaultForm.inviteCode = sessionStorage.getItem("INVITE_CODE");
      this.defaultForm.activityCode = this.$route.query.activityCode;
      getRoute(this.defaultForm).then(res => {
        if (res.code === 200) {
          window.open(res.result, '_blank');
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ivu-input-large {
  color: #222222;
  font-size: 20px;
  height: 68px;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid rgb(255, 24, 107);
}

.wrapper-page {
  width: 100%;
  height: 100%;
  background-color: #FF72A4;
  display: flex;
  align-items: center;

  .left-wratter {
    width: 50%;
    height: 100%;
    min-height: 1080px;
    display: flex;
    justify-content: center;
    align-items: center;

    .login-img {
      width: 100%;
      height: auto;
      // width: 636px;
      // height: 728px;
    }
  }

  .right-wrapper {
    width: 50%;
    height: 100%;
    min-height: 1080px;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 90px 190px;

    .right-content {
      text-align: center;

      .logo-img {
        width: 275px;
        height: 66px;
        margin-bottom: 64px;
      }

      .title-text {
        font-size: 32px;
        color: rgb(255, 24, 107);
        font-weight: 500;
        text-align: left;
      }

      .div-input {
        margin: 24px 0;
        text-align: left;

        .label {
          margin-bottom: 8px;
          color: @t-title-color;
          font-size: 16px;
          font-weight: 500;
        }

        .code-wrap {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .code {
            width: 102px;
            height: 44px;
            margin-left: 16px;
            background: #ffffff;
            border-radius: 4px 4px 4px 4px;
            opacity: 1;
            overflow: hidden;
            cursor: pointer;
            border: 1px solid @t-table-border-color;

            img {
              display: block;
              width: 100%;
              height: 100%;
            }
          }
        }
      }

      .fun {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 16px;
        margin-bottom: 26px;

        &-item {
          color: @t-title-color;
          font-size: 20px;

          &:hover {
            color: @primary-color;
          }
        }

        .text-tips {
          font-size: 20px;
          color: #FF186B;
        }
      }

      .btn {
        background: #FF186B;
        border-color: #FF186B;
        height: 68px;
        font-size: 26px;
        border-radius: 10px;
      }

      .other-text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 18px;
        color: #CDCDCD;
        line-height: 21px;
        margin: 20px 0;
      }

      .login-way {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 14px;

        .way {
          margin: 0 56px;
          display: flex;
          align-items: center;
          gap: 24px;

          img {
            display: block;
            width: 32px;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
